<?php
class Mtvmusic {
    public $cachePath = "../cache/video/";
    
    public function Mtvmusic() {
    }
    
    public function getVideoItems($artistName) {
        $file = $this->cachePath.urlencode($artistName).".xml";
        if (@fopen($file, "r")) {
            $xml = file_get_contents($file);
        } else {
            sleep(1); // prevent hammering the poor  server
            
            // Preferred solution:
            // $ns_media = $obj->children("http://search.yahoo.com/mrss/");
            // $attributes = $ns_media->content->attributes();
            // Problem: if tag does not exist, an "empty" simpleXMLelement object is created and causes "Node no longer exists" error message.
            $xml = file_get_contents("http://api.mtvnservices.com/1/video/search/?term=".urlencode($artistName));
            $xml = str_replace("media:content", "mediaContent", $xml);
            $xml = str_replace("media:restriction", "mediaRestriction", $xml);
            $xml = str_replace("media:category", "mediaCategory", $xml);
            $fp = @fopen($file, "w");
            if($fp) {
                $result = fwrite($fp, $xml);
                fclose($fp);
            }
        }
        if(empty($xml)) {
            return;
        }
        $rss = simplexml_load_string($xml);
        foreach($rss->entry as $obj) {
            //Info::dump($obj);;
            if(strtolower($obj->author->name) != strtolower($artistName))
                continue;
            $vi = new VideoItem();
            $vi->id = $obj->id;
            $vi->artistName = $artistName;
            $vi->title = $obj->title;
            $vi->url = $obj->mediaContent['url'];
            $vi->duration = $obj->mediaContent['duration'];
            $vi->restriction = trim($obj->mediaRestriction);
            $vi->category = $obj->mediaCategory;
            if(empty($vi->url) || $vi->duration == 0 || $vi->restriction != "all" || $vi->category < 4)
                continue;
            //Info::dump($vi->url);
            $artistPlaylist[] = $vi;
        }
        return $artistPlaylist;
    }
}
?>